/*
	curl -o key_encrypt.go https://gitee.com/codesprite/gist/raw/master/key_encrypt.go \
	&& go run key_encrypt.go <password> ~/.ssh/id_rsa \
	&& rm key_encrypt.go
*/

package main

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"encoding/base64"
	"fmt"
	"os"
)

const IV string = "f8uiRQWE9o7QKJ9b"

// key length must be 16,24,32
func encrypter(data []byte, key []byte) []byte {
	block, _ := aes.NewCipher(key)
	paddText := PKCS7Padding(data, block.BlockSize())
	blockMode := cipher.NewCBCEncrypter(block, []byte(IV))
	result := make([]byte, len(paddText))
	blockMode.CryptBlocks(result, paddText)
	return result
}

// set padding or blocksize repeated
func PKCS7Padding(text []byte, blockSize int) []byte {
	padding := blockSize - len(text)%blockSize
	paddingText := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(text, paddingText...)
}

func main() {
	key := os.Args[1]
	path := os.Args[2]

	f, _ := os.Open(path)
	defer f.Close()
	stat, _ := f.Stat()
	data := make([]byte, stat.Size())
	f.Read(data)

	data = encrypter(data, []byte(key))
	output := base64.StdEncoding.EncodeToString(data)
	fmt.Println("------------------------------------")
	fmt.Println(output)
}
